package com.tzstcl.sys.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tzstcl.base.model.AjaxResult;
import com.tzstcl.base.service.impl.BaseServiceImpl;
import com.tzstcl.framework.constants.AppConstants;
import com.tzstcl.framework.redis.RedisService;
import com.tzstcl.sys.user.mapper.SysUserMapper;
import com.tzstcl.sys.user.mapper.SysUserRoleMapper;
import com.tzstcl.sys.user.model.*;
import com.tzstcl.sys.user.service.SysRolePermissionService;
import com.tzstcl.sys.user.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 作者：guohy
 * 日期：2019年08月08日
 * 说明：用户表ServiceImpl
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    @Autowired
    private SysDeptPostService sysDeptPostService;

    @Autowired
    private RedisService redisService;

    /**
     * 批量增加用户表
     *
     * @param sysUserList
     * @return Integer 插入的记录数
     * @author guohy
     * @date 2019年08月08日
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    @Override
    public Integer insertBatch(List<SysUser> sysUserList) {
        return this.mapper.insertBatch(sysUserList);
    }

    @Override
    public SysUser findByNameOrPass(SysUser sysUser) {
        return mapper.findByNameOrPass(sysUser);
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void save(SysUser sysUser, Long[] ids) {
        if (null == sysUser.getId()) {
            sysUser.setPassword(AppConstants.SYSTEM_PASSWARD);
        }
        //不填入密码时不做更改
        if (StringUtils.isNotBlank(sysUser.getPassword())) {
            sysUser.setPassword(new Sha256Hash(sysUser.getPassword()).toHex());
        }
        if (null == sysUser.getId()) {
            sysUser.preInit();
            mapper.insert(sysUser);
        }
        else {
            sysUser.preInit();
            mapper.update(sysUser);
            sysUserRoleMapper.deleteById(sysUser.getId() + "");
            sysDeptPostService.delete(sysUser.getId());
        }
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        SysUserRole sysUserRole = null;
        for (Long id : ids) {
            sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setRoleId(id);
            list.add(sysUserRole);
        }
        sysUserRoleMapper.save(list);
        // 新增 部门信息
        SysDeptPost sysDeptPost = new SysDeptPost();
        sysDeptPost.setUserId(sysUser.getId());
        sysDeptPost.setDeptId(sysUser.getDeptId());
        sysDeptPost.setPostId(sysUser.getPostId());
        sysDeptPost.setPositionId(sysUser.getPositionId());
        sysDeptPostService.save(sysDeptPost);
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Integer delete(String[] ids) {
        mapper.delete(ids);
        return sysUserRoleMapper.delete(ids);
    }

    public Set<String> queryPermissions(Long id) {
        List<String> permsList = new ArrayList<>();
        // 查询角色id集合
        List<SysUserRole> roleList = null;
        //系统管理员，拥有最高权限
        if (Objects.equals(AppConstants.SUPER_ADMIN, id)) {
            permsList.add("*:*");
        }
        else {
            roleList = sysUserRoleMapper.findList(id);
            if (roleList.size() > 0) {
                redisService.set(AppConstants.USER_ROLE_CACHE + id, roleList);
                List<Long> roleIds = new ArrayList<Long>();
                for (SysUserRole userRole : roleList) {
                    roleIds.add(userRole.getRoleId());
                }
                if (roleIds.size() > 0) {
                    // 查询角色下所有菜单id结合
                    List<SysRolePermission> list = sysRolePermissionService.findPermissionList(roleIds);
                    permsList = new ArrayList<String>();
                    for (SysRolePermission rolePermission : list) {
                        permsList.add(rolePermission.getPermission());

                    }
                }
            }
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<String>();
        if (permsList != null && permsList.size() != 0) {
            for (String perms : permsList) {
                if (StringUtils.isNotBlank(perms)) {
                    permsSet.add(perms);
                }
            }
        }
        return permsSet;
    }

    @Override
    public SysUser compareUser(SysUser sysUser) {
        return mapper.compareUser(sysUser);
    }

    @Override
    public PageInfo<UserInfo> selectUserInfoPage(UserInfo userInfo) {
        PageHelper.startPage(userInfo.getPageNum(), userInfo.getPageSize());
        return PageInfo.of(mapper.selectUserInfo(userInfo));
    }

    @Override
    public PageInfo<SysUser> accountList(SysUser sysUser) {
        PageHelper.startPage(sysUser.getPageNum(), sysUser.getPageSize());
        return PageInfo.of(mapper.accountList(sysUser));
    }

    @Override
    public List<Map<String, Object>> getAddressBook(Long deptId) {
        return mapper.getAddressBook(deptId);
    }

    @Override
    public List<Map<String, Object>> getDeptAddressBook(Long deptId) {
        return mapper.getDeptAddressBook(deptId);
    }

    @Override
    public List<Map<String, Object>> getDeptUserList(Long deptId) {
        return mapper.getDeptUserList(deptId);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public AjaxResult updatePassword(String oldPassword, String newPassword, Long id) {
        String oldPasswordHex = new Sha256Hash(oldPassword).toHex();
        String newPasswordHex = new Sha256Hash(newPassword).toHex();
        SysUser user = mapper.getOne(id);
        if (null != user) {
            if (!oldPasswordHex.equals(user.getPassword())) {
                return AjaxResult.error("旧密码输入有误");
            }
            SysUser sysUser = new SysUser();
            sysUser.setId(id);
            sysUser.setPassword(newPasswordHex);
            mapper.updatePassword(sysUser);
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("当前用户不存在");
    }

    @Override
    public SysUser findByNameIgnoreDelFlag(SysUser sysUser) {
        return mapper.findByNameIgnoreDelFlag(sysUser);
    }
}